package com.hsj.goldstore.base;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hsj.goldstore.utils.Helper;

/**
 * Created by Administrator on 2018/3/25.
 */

public abstract class BaseMvpFrament<P extends IPresenter<V>, V extends BaseMvpView> extends Fragment implements BaseMvpView, LoaderManager.LoaderCallbacks<P> {

    private static final int BASE_LOAD_CODE = 1001;
    protected P presenter;
    private boolean isFirst = true;
    protected ProgressDialog progressDialog;

    /**
     * @return 获取布局contentView
     */
    protected abstract int getResouseId();

    /**
     * 资源初始化，和事件绑定
     */
    protected abstract void initView();

    /**
     * 数据初始化
     */
    protected abstract void initData();

    public View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(getResouseId(), container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (null != parent) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(BASE_LOAD_CODE, null, this);
        progressDialog = new ProgressDialog(getActivity());
    }

    @Override
    public void onStart() {
        super.onStart();
        presenter.attachView((V) this);
        if (isFirst) {
            isFirst = false;
            initView();
            initData();
        }
    }

    @Override
    public void onDestroy() {
        presenter.dettachView();
        super.onDestroy();
    }

    @Override
    public void onLoadFinished(Loader<P> loader, P data) {
        presenter = data;
    }

    @Override
    public void onLoaderReset(Loader<P> loader) {
        presenter = null;
    }

    @Override
    public void showError(String err) {
        Helper.showToast(getActivity(), err);
    }

    @Override
    public void showProgress(String msg) {
        if (null == progressDialog) {
            progressDialog = new ProgressDialog(getActivity());
        }
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.setCancelable(true);
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    @Override
    public void hideProgress() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
